#include "serveurapp.h"

#define PORT ("1234")
#define NBMAXCONNECTION (20)

ServeurApp::ServeurApp( int & argc, char ** argv ) : QCoreApplication(argc, argv), m_db("serv.db")
{
    connect(this, SIGNAL(aboutToQuit()), this, SLOT(cleanUp()));
    emptyDB();
}

int ServeurApp::exec()
{
    //QSqlQuery query(m_db);
    MySocket socket;
    socket.myBind(PORT);
    socket.myListen(NBMAXCONNECTION);

    while(true)
    {
        ClientHandler *client;

        struct sockaddr* addr = (sockaddr*)malloc(sizeof(struct sockaddr_in6));
        socklen_t length = sizeof(struct sockaddr_in6);

        try
        {
            MySocket clientSocket = socket.myAccept(addr, &length);

            if(length == sizeof(struct sockaddr_in6)) // si la connection est effectuée via une ipv6
            {

                    client = new ClientHandler(clientSocket, m_db, ((sockaddr_in6*)addr)->sin6_addr);
            }
            else // si la connection est effectuée via une ipv4
            {
                client = new ClientHandler(clientSocket, m_db, ((sockaddr_in*)addr)->sin_addr);
            }
            connect(this, SIGNAL(aboutToQuit()), client, SLOT(quit()));
            connect(client, SIGNAL(finished()), client, SLOT(deleteLater()));
            client->start();
        }
        catch (std::exception e)
        {
            std::cout<<"Failed to established connection with client. "<<e.what()<<std::endl;
        }

        free(addr);
    }

    return 0;
}

void ServeurApp::emptyDB()
{
    m_db.exec("DELETE FROM connexion");
    m_db.exec("DELETE FROM files");
}

void ServeurApp::cleanUp()
{
    emptyDB();
    m_db.close();
}
